import 'dart:convert';

import 'package:flutter_massage/common_lib/index.dart';
import 'package:flutter_massage/common_lib/routers/route.dart';
import 'package:flutter_massage/common_lib/utils/method_channel.dart';
import 'package:flutter_massage/pages/main/main_logic.dart';
import 'package:flutter_massage/pages/web/web_view.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart';

class JsChannelOperation {
  static void onMessageReceived(JavaScriptMessage message) {
    String msg = message.message;
    print('ylm - $msg');

    Map<String, dynamic> map = {};
    try {
      map = jsonDecode(msg);
    } catch (e) {
      if (msg.startsWith('{"')) return;
      if (msg.startsWith('{')) {
        msg = message.message.substring(1, message.message.length - 1);
      }
      if (msg.endsWith('}')) {
        msg = message.message.substring(0, message.message.length - 2);
      }
      List<String> result = msg.split(', ');
      for (var value in result) {
        List<String> result1 = value.split(': ');
        if (result1.isNotEmpty) {
          if (result1.length == 1 && result1.first.trim().notEmpty) {
            map[result1.first.trim()] = '';
          }
          if (result1.length > 1 && result1.first.trim().notEmpty) {
            String k = result1.first.trim();
            String v = result1[1].trim();
            if (v.isNotEmpty) {
              map[k] = v.toString();
            } else {
              map[k] = "";
            }
          }
        }
      }
    }

    jumpToPage(map);
  }

  static void jumpToPage(dynamic map) {
    ///跳出APP外部在 safari 中打开，type=5,url=要打开的链接：
    if (map['type'] == '5') {
      Uri? uri = Uri.tryParse(map['url']);
      if (uri == null) return;
      launchUrl(uri, mode: LaunchMode.externalApplication);
      return;
    }

    ///内部H5跳转，type=15,url=要打开的链接：
    if (map['type'] == '15') {
      String url = map['url'];
      if (url.empty) return;
      CommonRoute.open(WebH5Page(url: url));
      return;
    }

    ///重新获取消息未读数
    if (map['type'] == '999996') {
      Get.find<MainLogic>().refreshPreferredUnreadNum();
      return;
    }

    ///隐藏底部bar type=999997：
    if (map['type'] == '999997') {
      Get.find<MainLogic>().changeTabBarVisible(false);
      return;
    }

    ///显示底部bar type=999998：
    if (map['type'] == '999998') {
      Get.find<MainLogic>().changeTabBarVisible(true);
      return;
    }

    ///TD统计埋点 type=999999，两个参数：
    if (map['type'] == '999999') {
      XydMethodChannel.buryingPoint(map);
      return;
    }
  }
}
